﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace ProductSystem.Web
{
    /// <summary>
    /// DownloadFile 的摘要说明
    /// </summary>
    public class DownloadFile : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string filePath = context.Request["filePath"];
            string fileName = context.Request["fileName"];

            if (string.IsNullOrEmpty(filePath))
            {
                Alert(context, "请指定filePath参数!");
                return;
            }

            FileInfo downLoadFile = new FileInfo(filePath);
            if (!downLoadFile.Exists)
            {
                context.Response.Clear();
                context.Response.StatusCode = 404;
                context.Response.Write("指定目录下的文件未找到！");
                context.Response.End();
            }

            if (string.IsNullOrEmpty(fileName))
            {
                fileName = downLoadFile.Name;
            }

            context.Response.Clear();
            context.Response.ClearHeaders();
            context.Response.Buffer = false;
            context.Response.ContentType = "application/octet-stream";
            context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
            context.Response.AppendHeader("Content-Length", downLoadFile.Length.ToString());
            context.Response.WriteFile(downLoadFile.FullName);//DownloadFile.FullName保存文件名
            context.Response.Flush();
            context.Response.End();
            return;

        }


        private static void Alert(HttpContext context, string info)
        {
            context.Response.ContentType = "text/html";
            context.Response.Write("<html><head><script>window.alert('" + info + "');window.opener=null;window.open('','_self');window.close();</script></head><body></body></html>");
            context.Response.Flush();
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}